package servlet;

import bean.Course;
import dao.CourseDao;
import dao.UserDao;
import bean.User;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

public class ServletIndex extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // ① 初始化起始页参数
        int start = 0;
        int count = 5;

        // ② 接收并更新起始页参数
        try {
            start = Integer.parseInt(req.getParameter("start"));
        } catch (NumberFormatException e) {
            // 当浏览器没有传参数start时
        }

        // ③ 计算上一页和下一页的下标


        int total = new CourseDao().getTotal();

        // 起始参数+每页计数 = 下一页的ID
        int next = start + count;
        int pre = start - count;

        int last; // 末页下标

        // ④ 计算末页下标

        if (0 == total % count) {
            last = total - count;
        } else {
            last = total - total % count;
        }


        // ⑤ 处理边界问题
        pre = Math.max(pre, 0);
        next = Math.min(next, last);

        // ⑥ 向页面传递数据
        req.setAttribute("next", next);
        req.setAttribute("pre", pre);
        req.setAttribute("last", last);


        // 传递课程内容数据
        String title = "课程表管理";
        CourseDao courseDao = new CourseDao();

        // 从会话中获取存储的对象
        User user = (User) req.getSession().getAttribute("user");

        // 获取用户的课程信息
        List<Course> courseArrayList = courseDao.list(start, count,user);



        // 自定义排序[按lessonStart排序]
        Collections.sort(courseArrayList, new Comparator<Course>() {
            @Override
            public int compare(Course o1, Course o2) {
                return o1.getId() - o2.getId();

            }
        });


        req.setAttribute("title", title);
        req.setAttribute("courseArrayList", courseArrayList);
        req.getRequestDispatcher("index.jsp").forward(req, resp);
    }


}


class Items1 {
    Map<Integer, Items2> map1;

    public Items1(Map<Integer, Items2> map1) {
        this.map1 = map1;
    }
}

class Items2 {
    Map<String, String> map2;

    public Items2(Map<String, String> map2) {
        this.map2 = map2;
    }
}
